package com.lagou.springboot_article.controller;

import com.lagou.springboot_article.pojo.Article;
import com.lagou.springboot_article.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ArticleController {

    @Autowired
    private ArticleRepository articleRepository;

    @RequestMapping("/index")
    public String toIndex(Model model,Integer page,Integer size){
        if (page == null || page <= 1){
            page = 0;
        }else {
            page--;
        }
        if (size == null || size <= 0){
            size = 3;
        }
        Pageable pageable  = PageRequest.of(page,size);
        Page<Article> articlesPage = articleRepository.findAll(pageable);
        model.addAttribute("list", articlesPage.getContent());
        int totalPages = articlesPage.getTotalPages();
        if (page >= totalPages){
            page = totalPages -1;
        }
        model.addAttribute("page", page+1);
        model.addAttribute("total", totalPages);
        return "/client/index";
    }
}
